﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;
using System.Diagnostics;
using PDFLibNet;
using System.Threading;

namespace WinFormStudy
{
    public class PDFKit
    {
        /// <summary>
        /// 将PDF文件指定页码范围(不可跳页)拷贝至新的PDF文件
        /// </summary>
        /// <param name="sourcePdfPath">PDF文件源路径</param>
        /// <param name="outputPdfPath">生成pdf文件目标路径</param>
        /// <param name="startPage">起始页码</param>
        /// <param name="endPage">结束页码</param>
        /// <returns>返回值判断是否执行成功</returns>
        public static bool CopyByPageNum1(string sourcePdfPath, string outputPdfPath, int startPage, int endPage)
        {
            bool result = false;
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;
            try
            {
                reader = new PdfReader(sourcePdfPath);
                sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));
                pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(outputPdfPath, FileMode.Create));
                sourceDocument.Open();
                for (int i = startPage; i <= endPage; i++)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 将PDF文件指定页码范围(不可跳页)拷贝至新的PDF文件
        /// </summary>
        /// <param name="source">PDF文件源路径</param>
        /// <param name="target">生成PDF文件目标路径</param>
        /// <param name="StartPage">起始页码</param>
        /// <param name="EndPage">结束页码</param>
        /// <returns>返回值判断是否执行成功</returns>
        public static bool CopyByPageNum2(string source, string target, int StartPage, int EndPage)
        {
            bool result = false;
            iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(source);
            Document document = new Document(reader.GetPageSizeWithRotation(StartPage)); //创建document对象 // 
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(target, FileMode.Create)); //实例化document对象 
            document.Open();
            int rotation;
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page;
            for (int i = 1; i <= StartPage; i++)
            {
                while (StartPage <= EndPage)
                {
                document.SetPageSize(reader.GetPageSizeWithRotation(StartPage));
                document.NewPage(); page = writer.GetImportedPage(reader, StartPage);
                rotation = reader.GetPageRotation(StartPage);
                if (rotation == 90 || rotation == 270)
                {
                    document.NewPage();
                    if (rotation == 90)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(StartPage).Height);
                    }
                    if (rotation == 270)
                    {
                        cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(StartPage).Width, 0);
                    }
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                StartPage++;
                }
            }
            try
            {
                document.Close();
                reader = null;
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 将PDF文件指定页码范围(可跳页)拷贝至新的PDF文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="pageNums"></param>
        /// <returns>返回值判断是否执行成功</returns>
        public static bool CopyByPageNum3(string source, string target, int[] pageNums)
        {
            bool result = false;
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;
            try
            {
                reader = new PdfReader(source);
                sourceDocument = new Document(reader.GetPageSizeWithRotation(pageNums[0]));
                pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(target, FileMode.Create));
                sourceDocument.Open();
                foreach (int pageNumber in pageNums)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// PDF有多少页拆分成多少个pdf文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="targetFolder"></param>
        /// <returns>返回值判断是否执行成功</returns>
        public static bool PDFSplit(string source, string targetFolder)
        {
            bool result = false;
            string sourceFileName = Path.GetFileNameWithoutExtension(source);
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;
            int PageCount = 0;
            try
            {
                reader = new PdfReader(source);
                PageCount = reader.NumberOfPages;

                sourceDocument = new Document(reader.GetPageSizeWithRotation(1));
                for (int i = 1; i <= PageCount; i++)
                {
                    pdfCopyProvider = new PdfCopy(sourceDocument, new FileStream(Path.Combine(targetFolder, i + ".pdf"), FileMode.Create));
                    sourceDocument.Open();
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// PDF文件转SWF文件
        /// </summary>
        /// <param name="sourcePath">pdf文件源路径</param>
        /// <param name="targetPath">生成swf文件目标路径</param>
        /// <returns>返回值判断是否执行成功</returns>
        public static bool PDF2SWF(string sourcePath, string targetPath)
        {
            bool result = false;
            string toolPath = "C://Program Files (x86)/SWFTools/pdf2swf.exe";
            Process pc = new Process();

            string cmd = toolPath;
            string args = " -t " + sourcePath + " -s flashversion=9 -o " + targetPath;
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
                psi.WindowStyle = ProcessWindowStyle.Hidden;
                pc.StartInfo = psi;
                pc.Start();
                pc.WaitForExit();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
                throw new Exception(ex.Message);
            }
            finally
            {
                pc.Close();
                pc.Dispose();
            }
            return result;
        }

        /// <summary>
        /// PDF拆分生成Jpg文件
        /// </summary>
        /// <param name="source">PDF文件路径</param>
        /// <param name="targetFolder">目标文件夹</param>
        /// <returns>是否生成成功</returns>
        public static bool PDFSplit2Jpg(string source, string targetFolder)
        {
            bool result = false;
            PDFWrapper pdfWrapper = new PDFWrapper();
            try
            {                
                pdfWrapper.LoadPDF(source);
                int pagecount = pdfWrapper.PageCount == 0 ? 1 : pdfWrapper.PageCount;
                int Dpi = 150, Qua = 90;
                for (int i = 1; i <= pagecount; i++)
                {
                    pdfWrapper.ExportJpg(Path.Combine(targetFolder, i + ".jpg"), i, i, Dpi, Qua);//这里可以设置输出图片的页数、大小和图片质量
                    while (pdfWrapper.IsJpgBusy)
                    {
                        Thread.Sleep(5);
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                result = false;
            }
            pdfWrapper.Dispose();
            return result;
        }
    }
}
